const URL = 'https://www.oybtrip.com';

//const URL = 'https://app2.natapp4.cc';

//https://www.oybtrip.com

//https://app2.natapp4.cc

App({
  onLaunch(options) {
    console.info('App onLaunch----------------');
    console.log(JSON.stringify(options.query));
    this.onOpenAPIHandler();
    this.getPhoneNumber2();
  },
  onShow(options) {
    // 从后台被 scheme 重新打开
    // options.query == {number:1}

    console.info('App onShow----------------');
    console.log(JSON.stringify(options.query));
  },
  globalData:{
    nickName: '', //用户昵称
    avatar: '', //用户头像
    user_id:'',//支付宝用户ID
    name:'',//姓名
    idCard:'',//身份证号
    isLogin: false, //是否登录
    isAvatar: false, //是否获取头像
    smrz:false,//实名认证状态
    mobile:'',//手机号
    URL:URL,
    tenant_id:'',
    tenant_name:'橙黄蓝出行',
    baseUrl:URL,
    isAvatarLoading: false, //获取头像loading
    isLoginLoading: false, //
    isPhoneLoading:false,
    paymentHistory: null, //支付历史记录
    uid: null, //用户ID
   },

   getReal(){
    my.httpRequest({
      url: `${URL}/app-api/chl/app/getAlipayUserSeal`,
      data: {
        phone:this.globalData.mobile,
      },
      headers:{"tenant-id":"1",
      'content-type': 'application/x-www-form-urlencoded'},
      success: (res) => {
        if (res.data.data) {
          console.log(res.data.data);
          console.log("1-------"+this.globalData.smrz);
          var smrz = res.data.data.realNameStatus;
          var name = res.data.data.userName;
          var idCard = res.data.data.idCard;
          if(smrz=="true"){
            this.globalData.smrz = true;
            this.globalData.name = name;
            this.globalData.idCard = idCard;
            console.log("2-------"+this.globalData.smrz);
          }else{
            this.globalData.smrz = false;
          }
        }else{
          //this.setData({smrz:false});
          this.globalData.smrz = false;
        }
      },
      fail: (err) => {
        my.alert({'content':'认证失败'});
        //this.setData({smrz:false});
        this.globalData.smrz = false;
      }
    });
    
  },

     /**
   *
   * 调用JSAPI
   */
  onJSAPIHandler() {
    this.setData({
      isAvatarLoading: true
    });
    if (!this.data.isAvatar) {
      try {
        const user = this.getAvatarHandler();
        this.getPhoneNumber();
        this.globalData.nickName = user.nickName;
        this.globalData.avatar = user.avatar;
        this.setData({
          nickname: user.nickName,
          avatar: user.avatar,
          isAvatar: true,
          isAvatarLoading: false,
        });
      } catch (error) {
        console.error(error);
        this.toast(error.message);
        this.setData({
          nickname: '账户名',
          avatar: '',
          isAvatar: false,
          isAvatarLoading: false,
          mobile:'',
        });
      }
    } else {
      this.setData({
        nickname: '账户名',
        avatar: '',
        isAvatar: false,
        isAvatarLoading: false,
        mobile:'',
      });
    }
  },
  /**
   *  调用OPENAPI
   *
   */
  onOpenAPIHandler() {
    this.globalData.isLoginLoading=true;
    if (!this.globalData.isLogin) {
      try {
        const user = this.getLoginUserHandler();
        this.getPhoneNumber();
        this.globalData.nickName = user.nickName;
        this.globalData.avatar = user.avatar;
        this.globalData.user_id = user.userId;

        this.globalData.uid = user.userId;
        this.globalData.isLogin = true;
        
        this.globalData.nickname=user.nickName;
        this.globalData.avatar=user.avatar;
        this.globalData.isLogin=true;
        this.globalData.isLoginLoading=false;
      
      } catch (error) {
        console.error(error);
        this.toast(error.message);
        this.setData({
          nickname: '账户名',
          avatar: '',
          isLogin: false,
          isLoginLoading: false,
          mobile:'',
        });
      }
    } else {
      this.globalData.isLogin = false;
      this.setData({
        nickname: '账户名',
        avatar: '',
        isLogin: false,
        isLoginLoading: false,
        isAvatar: false,
        mobile:'',
      });
    }
  },
  async getLoginUserHandler() {
    return new Promise(async (resolve, reject) => {
      try {
        const auth = await this.getAuthCode(['auth_user']);
        const user = await this.getLoginUserInfo(auth.authCode);


        this.globalData.nickName = user.nickName;
        this.globalData.avatar = user.avatar;
        this.globalData.user_id = user.userId;

        this.globalData.uid = user.userId;
        this.globalData.isLogin = true;
        
        this.globalData.nickname=user.nickName;
        this.globalData.avatar=user.avatar;



        resolve(user);
      } catch (error) {
        console.log('error', error);
        reject(error);
      }
    });
  },
  getLoginUserInfo(authCode) {
    
    return new Promise((resolve, reject) => {
      my.httpRequest({
        url: `${URL}/app-api/chl/app/alipayUserInfo`,
        data: {
          authCode: authCode
        },
        headers:{"tenant-id":"1"},
        success: (res) => {
          if (!res.data.success) {
            reject({
              message: '登录失败',
              res
            });
          }
          resolve(res.data);
        },
        fail: (err) => {
          reject({
            message: '用户登录失败',
            err
          });
        }
      });
    });
  },
  getAvatarHandler() {
    return new Promise(async (resolve, reject) => {
      try {
        await this.getAuthCode('auth_user');
        const user = await this.getAuthUserInfo();
        resolve(user);
      } catch (error) {
        reject(error);
      }
    });
  },

  getAuthCode(scope) {
    return new Promise((resolve, reject) => {
      my.getAuthCode({
        scopes: scope,
        success: (auth) => {
          resolve(auth);
        },
        fail: (error) => {
          reject({
            message: '用户取消授权',
            error
          });
        }
      });
    });
  },
  getAuthUserInfo() {
    return new Promise((resolve, reject) => {
      my.getAuthUserInfo({
        success: (user) => {
          resolve(user);
        },
        fail: (error) => {
          reject({
            message: '获取用户头像失败',
            error
          });
        }
      });
    });
  },
  toast(message) {
    my.showToast({
      content: message,
      duration: 3000
    });
  },
  getPhoneNumber2() {
    console.info("获取手机号-------------");
    this.getPhoneNumber();
   
  },

  getPhoneNumber(){
    // //this.getAuthCode(`phoneNumber`);
    // my.getPhoneNumber({
    //   success: (res) => {
    //     console.log(res);
    //     console.log("处理获取手机号成功的逻辑");
    //   },
    //   fail: (error) => {
    //     console.log(error);
    //     // 处理获取手机号失败的逻辑
    //   }
    // });
    var that=this;
    my.getPhoneNumber({
 //     scopes: ['phoneNumber'],
      success: (res) => {
        let encryptedData = res.response;

        let params={
          encryptedData:res.response,
          sign:res.sign
        };

        my.request({
          url: `${URL}/app-api/chl/app/getPhone`,
          method: 'GET',
          data: params,
          headers:{"tenant-id":"1"},
          success: function (res) {
            let tel2 = res.data.mobile;
            if(tel2==null){
              my.navigateTo({
                url: '/pages/mine/components/sq/sq',
              })
            }
            that.globalData.mobile = tel2+'';
            console.log("手机号----"+tel2);
            that.getReal();
          },
        })
      },
      fail: (res) => {
        console.log(res);
      },
    });
    //my.alert({content:'用户id  -  '+app.globalData.user_id});
},
// 拒绝手机号
errorPhoneNumber(e){
  console.log('拒绝授权',e)

},
// 授权身份证号
getIDNumber(){
  var that=this;
	my.getIDNumber({
    scopes: 'IDNumber',
		success: async (res) => {
			console.log('授权成功',res)
      let encryptedData = res.response;

        let params={
          encryptedData:res.response,
          sign:res.sign
        };
      
        my.request({
          url: `${URL}/app-api/chl/app/getIdNumber`,
          method: 'GET',
          data: params,
          headers:{"tenant-id":"1"},
          success: function (res) {
            my.alert({content:res.data});
            let idStr = res.data.IDNumber
            this.globalData.IDNumber = idStr;
            that.setData({
              IDNumber:idStr
            });
   
          },
        })

		},
		fail: (err) => {
			console.log('授权失败',err)
		}
	})
},
// 拒绝身份证号
errorIDNumber(e){
	console.log('拒绝授权',e)
}
  
});
